package com.ydlclass.factory.proxy;

import com.ydlclass.message.YrpcMessage;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author it楠老师
 * @createTime 2023-03-23
 */
public class PendingRequests {


    private static PendingRequests pendingRequests = new PendingRequests();

    public static PendingRequests getInstance(){
        return pendingRequests;
    }

    private static final Map<Long, CompletableFuture<YrpcMessage>> PENDING_FUTURES = new ConcurrentHashMap<>();

    public void put(Long requestId, CompletableFuture<YrpcMessage> future) {
        PENDING_FUTURES.put(requestId, future);
    }

    public void complete(YrpcMessage yrpcMessage) {
        CompletableFuture<YrpcMessage> future = PENDING_FUTURES.remove(yrpcMessage.getRequestId());
        if (null != future) {
            future.complete(yrpcMessage);
        } else {
            throw new IllegalStateException();
        }
    }

}
